import React, { useEffect, useState } from "react";
import logo from "@/assets/logo.svg";
import styles from "./Header.module.css";
import { Layout, Typography, Input, Menu, Button, Dropdown } from "antd";
import { GlobalOutlined } from "@ant-design/icons";
// import store from "@/redux/store";
import {
  addLanguageActionCreator,
  changeLanguageActionCreator,
} from "@/redux/language/languageActions";
// ! 从store中连接state数据
import { useSelector } from "../../redux/hooks";
import { useDispatch } from "react-redux";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import jwt_decode, { JwtPayload as DefaultJwtPayload } from "jwt-decode";
import { userSlice } from "../../redux/user/slice";

// ! 自定义自己的jwtpayload
interface JwtPayload extends DefaultJwtPayload {
  username: string;
}

export const Header: React.FC = () => {
  // ?不需要再订阅了 使用了react-redux的useSelector
  // const state = store.getState();

  // const [languageList, setLanguageList] = useState(state.languageList);
  // const [language, setLanguage] = useState(state.language);

  // ? 每次都要指定store的类型 组件和store绑定起来了,需要使用TypedUseSelectorHook接口进行解耦
  const { language, languageList } = useSelector((state) => state.language);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [username, setUsername] = useState<string>("");

  // ! 11-10 使用redux
  const jwt = useSelector((s) => s.user.token);
  // 安装插件jwt-decode 进行解码 拿到解密的数据

  const shoppingCartItems = useSelector((s) => s.shoppingCart.items);
  const shoppingCartLoading = useSelector((s) => s.shoppingCart.loading);

  useEffect(() => {
    if (jwt) {
      const token = jwt_decode<JwtPayload>(jwt);
      setUsername(token.username);
    }
  }, [jwt]);

  const handleMenuClick = (e) => {
    console.log("click", e);
    if (e.key === "new") {
      // const action = {
      //   type: "add_language", // 消息类型
      //   payload: { code: "new_code", name: "新语言" }, // 向store传递的数据
      // };
      const action = addLanguageActionCreator("新语言", "new_code");
      // store.dispatch(action); // 分发数据给store
      dispatch(action);
    } else {
      // const action = {
      //   type: "change_language", // 消息类型
      //   payload: e.key, // 向store传递的数据
      // };
      const action = changeLanguageActionCreator(e.key);
      // store.dispatch(action); // 分发数据给store
      dispatch(action);
    }
  };

  const onLogout = () => {
    dispatch(userSlice.actions.logOut());
    navigate("/");
  };

  /** 订阅store */
  // store.subscribe(() => {
  //   const state1 = store.getState();
  //   setLanguage(state1.language);
  //   setLanguageList(state1.languageList);
  //   console.log("store change");
  // });

  return (
    <div className={styles.App}>
      <div className={styles["app-header"]}>
        {/* top-header */}
        <div className={styles["top-header"]}>
          <div className={styles.inner}>
            <Typography.Text>让旅游更幸福</Typography.Text>
            <Dropdown.Button
              style={{ marginLeft: 15 }}
              overlay={
                <Menu onClick={handleMenuClick}>
                  {languageList.map((item) => (
                    <Menu.Item key={item.code}>{item.name}</Menu.Item>
                  ))}
                  <Menu.Item key="new"> {t("header.add_new_language")}</Menu.Item>
                </Menu>
              }
              icon={<GlobalOutlined />}
            >
              {languageList.find((item) => item.code === language)?.name}
            </Dropdown.Button>
            {jwt ? (
              <Button.Group className={styles["button-group"]}>
                <span>
                  {t("header.welcome")}
                  <Typography.Text strong>{username}</Typography.Text>
                </span>
                <Button
                  loading={shoppingCartLoading}
                  onClick={() => {
                    navigate("/shoppingCart");
                  }}
                >
                  {t("header.shoppingCart")}
                  {(shoppingCartItems && shoppingCartItems.length) || 0}
                </Button>
                <Button onClick={onLogout}>{t("header.signOut")}</Button>
              </Button.Group>
            ) : (
              <Button.Group className={styles["button-group"]}>
                <Button onClick={() => navigate(`/register`)}>注册</Button>
                <Button onClick={() => navigate(`/signIn`)}>登陆</Button>
              </Button.Group>
            )}
          </div>
        </div>
        <Layout.Header className={styles["main-header"]}>
          <img src={logo} alt="logo" className={styles["App-logo"]} />
          <Typography.Title level={3} className={styles.title}>
            React旅游网
          </Typography.Title>
          <Input.Search
            placeholder={"请输入旅游目的地、主题、或关键字"}
            className={styles["search-input"]}
            onSearch={(keywords) => {
              console.log("wwwww", keywords);
              navigate(`/search/${keywords}`);
            }}
          />
        </Layout.Header>
        <Menu mode={"horizontal"} className={styles["main-menu"]}>
          <Menu.Item
            key="1"
            onClick={() => {
              navigate("/");
            }}
          >
            {" "}
            {t("header.home_page")}{" "}
          </Menu.Item>
          <Menu.Item key="2"> {t("header.weekend")} </Menu.Item>
          <Menu.Item key="3"> {t("header.group")} </Menu.Item>
          <Menu.Item key="4"> {t("header.backpack")} </Menu.Item>
          <Menu.Item key="5"> {t("header.private")} </Menu.Item>
          <Menu.Item key="6"> {t("header.cruise")} </Menu.Item>
          <Menu.Item key="7"> {t("header.hotel")} </Menu.Item>
          <Menu.Item key="8"> {t("header.local")} </Menu.Item>
          <Menu.Item key="9"> {t("header.theme")} </Menu.Item>
          <Menu.Item key="10"> {t("header.custom")} </Menu.Item>
          <Menu.Item key="11"> {t("header.study")} </Menu.Item>
          <Menu.Item key="12"> {t("header.visa")} </Menu.Item>
          <Menu.Item key="13"> {t("header.enterprise")} </Menu.Item>
          <Menu.Item key="14"> {t("header.high_end")} </Menu.Item>
          <Menu.Item key="15"> {t("header.outdoor")} </Menu.Item>
          <Menu.Item key="16"> {t("header.insurance")} </Menu.Item>
        </Menu>
      </div>
    </div>
  );
};
